//
//  SearchPurchaseController.m
//  MedicineBox
//
//  Created by dllo on 15/9/20.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SearchPurchaseController.h"
#import "HomeModel.h"
#import "MedicineBoxDataBase.h"
#import "UIImageView+NightImage.h"
#import "UMSocial.h"
#import "PurchaseCell.h"
#import "AsyncConnection.h"
#import "UIImageView+WebCache.h"
#import "WebViewController.h"
#import "RecommendCell.h"
#import "CommentController.h"
#import "RecommdController.h"
#import "DKNightVersion.h"

@interface SearchPurchaseController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate,UMSocialDataDelegate>
@property (nonatomic, retain) UILabel *shareLabel;
@property (nonatomic, retain) NSDictionary *headerDic;
@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) NSMutableArray *tableArray;
@property (nonatomic, retain) HomeModel *model;
@property (nonatomic, retain) UIView *barView;
@property (nonatomic, retain) UINavigationController *nav;
@property (nonatomic, retain) UITabBarController *tab;
@property (nonatomic, retain) UILabel *collectionLabel;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, retain) NSDictionary *tableDic;
@property (nonatomic, retain) NSMutableArray *secondArray;
@end

@implementation SearchPurchaseController


- (void)dealloc
{
 
    [_secondArray release];
    [_tableDic release];
    [_shareLabel release];
    [_collectionLabel release];
    [_headerDic release];
    [_tableV release];
    [_tableArray release];
    [_barView release];
    [_tab release];
    [_nav release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.model = [[HomeModel alloc] init];
        self.tableArray = [NSMutableArray array];
        self.secondArray = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 5, 20, 20);
    [backButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"iconfont-fanhui-3" ofType:@"png"]] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 60) style:UITableViewStyleGrouped];
    self.tableV.dataSource = self;
    self.tableV.delegate = self;
    _tableV.nightBackgroundColor = UIColorFromRGB(0x343434);
    _tableV.nightSeparatorColor = UIColorFromRGB(0x313131);
    [self.view addSubview:_tableV];
    [_tableV release];
    [self creatTableHeaderView:_headerDic];
    
    [self webConnection];
    
    
}

- (void)creatTableHeaderView:(NSDictionary *)dic
{

    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 290)];
    backView.backgroundColor = [UIColor whiteColor];
    backView.nightBackgroundColor = UIColorFromRGB(0x343434);
    UIImageView *headerIV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 0, self.view.frame.size.width - 10, 170)];
    [backView addSubview:headerIV];
    
    self.tableV.tableHeaderView = backView;
    [backView release];
    [headerIV release];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, headerIV.frame.origin.y + headerIV.frame.size.height, self.view.frame.size.width, 20)];
    titleLabel.text = [dic objectForKey:@"name"];
    titleLabel.nightTextColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [backView addSubview:titleLabel];
    [titleLabel release];
    
    UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 60, titleLabel.frame.origin.y + titleLabel.frame.size.height, self.view.frame.size.width / 2 + 60, 20)];
    priceLabel.textColor = [UIColor colorWithRed:0.9 green:0.5 blue:0.3 alpha:1];
    priceLabel.nightTextColor = [UIColor redColor];
    priceLabel.text = [NSString stringWithFormat:@"%@元      已出售%@",[dic objectForKey:@"price"],[dic objectForKey:@"sellerCount"]];
    priceLabel.textAlignment = NSTextAlignmentCenter;
    [backView addSubview:priceLabel];
    [priceLabel release];
    
    UILabel *activityLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, priceLabel.frame.origin.y + priceLabel.frame.size.height, self.view.frame.size.width - 5, 30)];
    activityLabel.textColor = [UIColor brownColor];
    activityLabel.text = [NSString stringWithFormat:@"活动详情：%@",[dic objectForKey:@"activityDesc"]];
    activityLabel.nightTextColor = [UIColor whiteColor];
    activityLabel.font = [UIFont systemFontOfSize:12];

    [backView addSubview:activityLabel];
    [activityLabel release];
    
    
    UIButton *drugShopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    drugShopButton.frame = CGRectMake([[UIScreen mainScreen] bounds].size.width - 140, activityLabel.frame.origin.y + activityLabel.frame.size.height , 120, 30);
    [backView addSubview:drugShopButton];
    [drugShopButton addTarget:self action:@selector(drugButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *drugShopLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    drugShopLabel.textAlignment = NSTextAlignmentRight;
    drugShopLabel.font = [UIFont systemFontOfSize:12];
    drugShopLabel.textColor = [UIColor orangeColor];
    [drugShopButton addSubview:drugShopLabel];
    [drugShopLabel release];
    drugShopLabel.text = @"点击进入1号药店";
    drugShopLabel.nightTextColor = [UIColor orangeColor];
    
    for (NSString *key in dic) {
        
        if ([key isEqualToString:@"img"]) {
            
            [headerIV sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"img"]]];
            
        } else if ([key isEqualToString:@"imgUrl"]) {
        
        [headerIV sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"imgUrl"]]];
        
        }
        
    }
    


}

- (void)drugButtonAction:(id)semder
{

    NSDictionary *tempDic = [self.tableDic objectForKey:@"brandObj"];
    NSString *urlStr = [tempDic objectForKey:@"picurl"];
    WebViewController *webC = [[WebViewController alloc] init];
    webC.target = urlStr;
    [webC getSignal:@"我的一号药店"];
   [self presentViewController:webC animated:YES completion:^{
       
       
   }];
    
    

}



- (void)webConnection
{
    
       [AsyncConnection asyncConnectionWithUrl:self.url name:nil parameters:nil block:^(id data) {
        
        self.tableDic = [data objectForKey:@"data"];
        NSArray *commentArray = [[data objectForKey:@"data"] objectForKey:@"comment_list"];
        [self.tableArray addObject:commentArray];
        [self.tableV reloadData];
        
    } get:@"post"];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=recommendation.ProductDetailsRecommendAction&method=recommendation.ProductDetailsRecommendAction&itemId=%@&province=9&encryptversion=2&sign=4E0BA014C20EB94569B3A79A5B17A5EA&timestamp=20150918190729&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",[self.headerDic objectForKey:@"id"]];
    [AsyncConnection asyncConnectionWithUrl:urlStr name:nil parameters:nil block:^(id data) {
        
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"itemList"];
        [self.secondArray addObjectsFromArray:array];
        [self.tableV reloadData];
        
    } get:@"post"];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        
        static NSString *cellI = @"cellI";
        PurchaseCell *pC = [tableView dequeueReusableCellWithIdentifier:cellI];
        if (pC == nil) {
            
            pC = [[PurchaseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellI];
            
        }
        if (_tableArray.count != 0) {
            
            
            [pC getItem:[[self.tableArray objectAtIndex:0] objectAtIndex:indexPath.row]bigDic:self.tableDic];
            
        }
    pC.nightBackgroundColor = UIColorFromRGB(0x343434);
        return pC;
        
    } else if (indexPath.section == 1) {
    
        static NSString *cellI = @"RcellI";
        RecommendCell *pC = [tableView dequeueReusableCellWithIdentifier:cellI];
        if (pC == nil) {
            
            pC = [[RecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellI];
            
        }
        if (_secondArray.count != 0) {
            
            [pC getArray:self.secondArray];
            
        }
        
        pC.nightBackgroundColor = UIColorFromRGB(0x343434);
        pC.target = self;
        pC.action = @selector(recommendTapAction:);
        return pC;
    
    }
    
    return nil;
}


- (void) recommendTapAction:(NSDictionary *)dic
{

    NSString *str = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=products.getbaseinfo&itemcode=%@&flag=0&province=9&encryptversion=2&sign=01DE5C022E6E01EF39A79B2A4569D308&timestamp=20150918190726&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",[dic objectForKey:@"id"]];

    RecommdController *recommendC = [[RecommdController alloc] init];
    [recommendC getSearchUrl:str tab:self.tab nav:self.nav dic:dic];
    [recommendC creatTableHeaderView:dic];
    [self.navigationController pushViewController:recommendC animated:YES];
    [recommendC release];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (_tableArray.count != 0) {
        
        if (section == 0) {
            
            NSArray *tempArray = [self.tableArray objectAtIndex:0];
            return tempArray.count;
            
        }  if (section == 1) {
            
            return 1;
            
        }
        
    }
 
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    if (indexPath.section == 0) {
        
        if (_tableArray.count != 0) {
            
        
            NSDictionary *dic = [[_tableArray objectAtIndex:0] objectAtIndex:indexPath.row];
        CGFloat height = [self labelHeight: [dic objectForKey:@"content"] width:[[UIScreen mainScreen]bounds].size.width - 10];
            return height + 100;
            
        } else {
        
            return 100;
        
        }
        
    } if (indexPath.section == 1) {
        
        
        return 160;
        
    }
    
    
    return 0;
}

- (CGFloat)labelHeight:(NSString *)text width:(CGFloat)width
{
    
    CGSize size = CGSizeMake(width, 1000);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil];
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
    
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    if (section == 0) {
        
        NSString *str = [NSString stringWithFormat:@"累计评价(%@)                                        %@好评",[[_tableDic objectForKey:@"item_info"] objectForKey:@"usergradecount"],[_tableDic objectForKey:@"goodcomment_per"]];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.view.frame.size.width - 5 , 30)];
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor grayColor];
        label.text = str;
        label.userInteractionEnabled = YES;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(self.view.frame.size.width - 40, 5, 40, 20);
        [button setTitle:@"更多" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [label addSubview:button];
        
        return label;
        
    } else {
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.view.frame.size.width - 100, 30)];
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor grayColor];
        label.text = @"精品推荐";
        return label;
        
    }
    

}


- (void)moreButtonAction:(id)sender
{

    CommentController *commentC = [[CommentController alloc] init];
    commentC.idStr = [_headerDic objectForKey:@"id"];
    UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:commentC];
    [self presentViewController:navC animated:YES completion:^{
        
        
        
    }];
  

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 30;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 2;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
}

- (void)getSearchUrl:(NSString *)url tab:(UITabBarController *)tab nav:(UINavigationController *)nav dic:(NSDictionary *)dic
{

    self.headerDic = dic;
    _url = url;
    self.nav = nav;
    self.tab = tab;
    self.barView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)];
    _barView.backgroundColor = [UIColor colorWithRed:86/255.0 green:137/255.0 blue:156/255.0 alpha:1];
    
    [self.nav.view addSubview:_barView];
    [_barView release];
    
    self.model.namecn = [dic objectForKey:@"name"];
    self.model.titleimg = [dic objectForKey:@"img"];
    self.model.avgprice = [NSNumber numberWithInteger:[[dic objectForKey:@"price"] integerValue]];
    NSNumber *num = [NSNumber numberWithInteger:[[dic objectForKey:@"id"] integerValue]];
    self.model._id = [num description];
    self.model.type = @"mine";
    //分享
    
    UIButton *shareButton = [[UIButton alloc] initWithFrame:CGRectMake(60 , 5, 20, 20)];
    [shareButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"shareButton" ofType:@"png"]] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.barView addSubview:shareButton];
    self.shareLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, shareButton.frame.size.height + 5 , 60, 20)];
    _shareLabel.text = @"分享";
    _shareLabel.font = [UIFont systemFontOfSize:12];
    _shareLabel.textAlignment = NSTextAlignmentCenter;
    _shareLabel.textColor = [UIColor whiteColor];
    [_barView addSubview:_shareLabel];
    [shareButton release];
    [_shareLabel release];
    
    //收藏
    
    UIButton *collectButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 100, 5, 20, 20)];
    HomeModel *collectModel = [MedicineBoxDataBase selectOnlyWith:[NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]]];
    self.collectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(collectButton.frame.origin.x - 20, collectButton.frame.size.height + 5 , 60, 20)];
    _collectionLabel.font = [UIFont systemFontOfSize:12];
    _collectionLabel.textAlignment = NSTextAlignmentCenter;
    _collectionLabel.textColor = [UIColor whiteColor];
    [_barView addSubview:_collectionLabel];
   
    [_collectionLabel release];
    if (collectModel) {
        [collectButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"collectSuccess" ofType:@"png"]] forState:UIControlStateNormal];
        _collectionLabel.text = @"已收藏";
        
    }else
    {
        [collectButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cButton" ofType:@"png"]] forState:UIControlStateNormal];
        _collectionLabel.text = @"收藏";
        
    }
    [collectButton addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.barView addSubview:collectButton];
    [collectButton release];
   
    
   

}

//收藏点击事件
- (void)collectAction:(UIButton *)button
{
    if ([_collectionLabel.text isEqualToString:@"收藏"]) {
        [MedicineBoxDataBase insertWithModel:self.model];
        
        [button setBackgroundImage:[UIImage imageNamed:@"collectSuccess.png"] forState:UIControlStateNormal];
        _collectionLabel.text = @"已收藏";
    } else if ([_collectionLabel.text isEqualToString:@"已收藏"]) {
        
        [button setBackgroundImage:[UIImage imageNamed:@"cButton.png"] forState:UIControlStateNormal];
        [MedicineBoxDataBase deleteWith:self.model];
        _collectionLabel.text = @"已取消收藏";
    }
}

//分享点击事件
- (void)shareAction:(UIButton *)button
{
#pragma mark -
#pragma mark 截屏图片
    UIGraphicsBeginImageContext(self.view.bounds.size);     //currentView 当前的view  创建一个基于位图的图形上下文并指定大小为
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];//renderInContext呈现接受者及其子范围到指定的上下文
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();//返回一个基于当前图形上下文的图片
    UIGraphicsEndImageContext();//移除栈顶的基于当前位图的图形上下文
    UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);//然后将该图片保存到图片图
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55e0ffc5e0f55a9a44002606"
                                      shareText:@"你要分享的文字"
                                     shareImage:viewImage
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToEmail,UMShareToSms,nil]
                                       delegate:self];
}

- (void)didFinishGetUMSocialDataResponse:(UMSocialResponseEntity *)response
{
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [UMSocialSnsService  applicationDidBecomeActive];
    
}

- (void)backButtonAction:(id)sender
{

    [_barView removeFromSuperview];
    self.tab.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
